<?php
namespace Seller\Controller;
use Think\Controller;

class CustomerController extends CommonController
{
    public function _initialize()
    {
        // 数组存放不需添加进权限控制的方法
        // 注意：请把所有大写字母改成小写
        $params = array(
            'searchmanager'
        );
        parent::_initialize($params);
        $this->assign("now_module" ,"custom");
    }

    // 客户中心
    public function index()
    {
        $customer_d = D("CustomerView");
        // 查询出未转化的
        $me = session("manager_id");
        if(session("role_id") != 1){
            $where['_string'] = "customers.ai_manager = $me OR customers.wechat_manager = $me";
        }
        $where['customers.is_conversion'] = array("eq" ,0);
        $where['customers.c_status'] = array("eq" ,1);
        if(isset($_REQUEST['cName']))
        {
            $cName = trim(I('cName'));
            $aiName = trim(I('aiName'));
            $weName = trim(I('weName'));
            $to_agent = to_int(I('to_agent'));

            if($cName != ''){
                $cWhere['customers.c_name'] = array("like" ,"%$cName%");
                $cWhere['customers.mobile'] = array("like" ,"%$cName%");
                $cWhere['customers.wx_num'] = array("like" ,"%$cName%");
                $cWhere['_logic'] = 'or';
                $where['_complex'] = $cWhere;
            }
            if($to_agent != ''){
                $where['customers.is_conversion'] = array("eq" ,$to_agent);
            }
            if($aiName != ''){
                $aiusers = M("manager")->where("name LIKE '%$aiName%' AND m_status = 1")->select();
                if($aiusers){
                    $ais = array();
                    foreach($aiusers as $v){
                        $ais[] = $v["id"];
                    }
                    $where['customers.ai_manager'] = array("in" ,implode("," ,$ais));
                }
            }
            if($weName != ''){
                $weusers = M("manager")->where("name LIKE '%$aiName%' AND m_status = 1")->select();
                if($weusers){
                    $wes = array();
                    foreach($weusers as $val){
                        $wes[] = $val["id"];
                    }
                    $where['customers.wechat_manager'] = array("in" ,implode("," ,$wes));
                }
            }
        }
        $count = $customer_d->where($where)->count();
        $page = set_page($count, C('PAGE_NUM'));
        $customers = $customer_d->where($where)->limit($page->firstRow.','.$page->listRows)
            ->order('customers.c_id DESC')->select();

        $show = $page->show();
        $this->assign('page',$show);
        $this->assign('customers', $customers);
        $this->display();
    }

    // 转化成代理
    public function to_agent()
    {
        if(IS_POST)
        {
            $c_id = to_int(I("post.c_id"));
            $rank_id = to_int(I("post.rank_id"));
            $sex = to_int(I("post.sex"));
            $username = trim(I("post.username"));
            $pwd = trim(I("post.pwd"));
            // 未转化的代理
            $customer = M("customers")->where("c_id = $c_id AND is_conversion = 0")->find();
            if(!$pwd || !$customer){
                $this->error("参数有误" ,$_SERVER['HTTP_REFERER'] ,1);
            }
            if(!preg_match("/^[a-zA-z0-9\_]{3,50}$/" ,$username)){
                $this->error("用户名为3位以上的字母数字下划线" ,$_SERVER['HTTP_REFERER'] ,2);
            }
            // 通过用户名/手机查询是否已添加过改用户
            $agent = M("agent")->where("mobile  = '".$customer['mobile']."' OR username = '$username'")->find();
            if($agent){
                $this->error("已存在此代理，请仔细核对" ,U('Customer/index') ,1);
            }
            $salt = substr(md5(time().$username) ,-6);
            $rs = M("agent")->add(array(
                'agent_name' => $customer['c_name'],
                'rank_id' => $rank_id,
                'mobile' => $customer['mobile'],
                'username' => $username,
                'password' => md5(md5($pwd) .$salt),
                'salt' => $salt,
                'wx_num' => $customer['wx_num'],
                'sex' => $sex,
                'c_id' => $c_id,
                'reg_time' => time(),
                'reg_ip' => get_client_ip()
            ));
            if($rs !== false){
                // 转化成功请修改客户状态
                M("customers")->where("c_id = $c_id")->save(array("is_conversion" => 1));
                $this->success("转化成功" ,U('Customer/index') ,1);
            }else{
                $this->error("转化失败" ,$_SERVER['HTTP_REFERER'] ,1);
            }
        }else{
            $cid = to_int(I("get.id"));
            $this->ranks = M('agent_rank')->where("rank_status = 1")->order('rank_grade ASC')->select();
            $customer = M("customers")->where("c_id = $cid")->find();
            if(!$customer){
                $this->error("请求失败" ,$_SERVER['HTTP_REFERER'] ,1);
            }
            $this->assign("customer" ,$customer);
            $this->display();
        }
    }

    // 客户添加
    public function add_custom()
    {
        if(IS_POST)
        {
            $c_name = trim(I("post.c_name"));
            $mobile = to_int(I("post.mobile"));
            $wx = trim(I("post.wx_num"));
            $c_area = trim(I("post.c_area"));
            $wechat_manager = to_int(I("post.wechat_manager"));
            $keyword = trim(I("post.keyword"));
            $remark = trim(I("post.remark"));

            if($c_name == ''){
                $this->error("参数有误" ,$_SERVER['HTTP_REFERER'] ,1);
            }
            $rs = M("customers")->add(array(
                'ai_manager' => session("manager_id"),
                'wechat_manager' => $wechat_manager,
                'c_name' => $c_name,
                'mobile' => $mobile,
                'wx_num' => $wx,
                'c_area' => $c_area,
                'keyword' => $keyword,
                'remark' => $remark,
                'create_time' => date("Y-m-d H:i:s", time())
            ));
            if($rs !== false){
                if(isset($_POST['tp']) && $_POST['tp'] == 'stay'){
                    $this->success("添加成功" ,U('Customer/add_custom') ,1);
                }else{
                    $this->success("添加成功" ,U('Customer/index') ,1);
                }
            }else{
                $this->error("添加失败" ,$_SERVER['HTTP_REFERER'] ,1);
            }
        }else{
            $this->display();
        }
    }

    // 批量关闭客户
    public function del_custom()
    {
        if(IS_POST){
            $c_ids = I("post.c_id");
            if(!is_array($c_ids) || empty($c_ids)){
                $this->error("参数有误" ,U('Customer/index') ,1);
            }
            foreach($c_ids as $id){
                if(!_int($id)){
                    $this->error("参数有误" ,U('Customer/index') ,1);
                }
                $ids[] = $id;
            }
            $where["is_conversion"] = array("eq" ,0);
            $where["c_id"] = array("in" ,implode("," ,$ids));
            // 批量关闭
            $rs = M("customers")->where($where)->save(array("c_status" => 0));
            if($rs !== false){
                $this->success("操作成功" ,U('Customer/index') ,1);
            }else{
                $this->error("操作失败" ,U('Customer/index') ,1);
            }
        }else{
            exit("error");
        }
    }

    // 搜索管理
    public function searchManager()
    {
        $managerName = trim(I('post.aName'));
        if($managerName != ''){
            $managerList = M("manager")->where("name LIKE '%$managerName%' AND m_status = 1")->select();
            if($managerList) {
                $this->ajaxReturn($managerList);
            }
        }
    }
}